package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressbookMapper;
import com.sky.service.AddressbookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressbookServiceImpl implements AddressbookService {
    @Autowired
    private AddressbookMapper addressbookMapper;
    //新增地址
    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
       // 设置地址 “是否为默认地址”，默认值0为 “非默认”
        addressBook.setIsDefault(0);

        addressbookMapper.add(addressBook);
    }
   //查询地址
    @Override
    public List<AddressBook> select() {
      List<AddressBook>list=  addressbookMapper.select();
        return list;
    }
    //查询默认地址
    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        List<AddressBook> list=addressbookMapper.list(addressBook);
        return list;
    }

    @Override
    public void update(AddressBook addressBook) {
        addressbookMapper.update(addressBook);
    }
//根据id查询地址
    @Override
    public AddressBook selectById(Long id) {
       AddressBook addressBook= addressbookMapper.selectById(id);
        return addressBook;
    }

    @Override
    public void deleteID(Long id) {
       addressbookMapper.deleteID(id);
    }

    @Override
    public void setting(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        //想了半天这个作用
        //先将当前用户的所有地址取消默认状态，再将指定地址设为默认，避免出现 “多个默认地址” 的逻辑混乱
        addressbookMapper.updateIsDefaultByUserId(addressBook);// 批量修改

        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressbookMapper.update(addressBook);

    }


}
